const router = require("koa-router")();
const TokenManager = require("../utils/token");

router.get("/", async (ctx, next) => {
  await ctx.render("index", {
    title: "Hello Koa 2!",
  });
});

router.get("/test", async (ctx, next) => {
  ctx.body = "测试成功";
});

router.post("/testPost", async (ctx, next) => {
  ctx.body = {
    title: "koa2 testPost",
  };
});

router.get("/checkToken", async (ctx, next) => {
  try {
    // 从header中获取token
    const token = ctx.headers.authorization;
    if (!token) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: "未提供token",
      };
      return;
    }

    // 验证token
    const tokenInfo = await TokenManager.verifyToken(token);
    if (!tokenInfo) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: "token无效或已过期",
      };
      return;
    }

    ctx.body = {
      code: 200,
      message: "token有效",
      data: {
        username: tokenInfo.username,
        expiredAt: tokenInfo.expired_at,
      },
    };
  } catch (error) {
    console.error("验证token错误:", error);
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "服务器内部错误",
    };
  }
});

module.exports = router;
